<?php


namespace App\Exceptions;

//api 接口的错误提示
class ApiException  extends \Exception
{
    private $http_code = 200;
    /**
     * ApiException constructor.
     * @param string $message 错误信息
     * @param string $error_id 错误id
     * @param string $code http状态码
     */
    function __construct($message = '', $error_id = 'ERROR', $code = Handler::STATUS_BAD_REQUEST)
    {
        parent::__construct($message, Handler::STATUS_NORMAL);
        //self::http_code = $code;
        $this->setHttpCode($code);
        empty($error_id) || $this->error_id = $error_id;
    }

    private function setHttpCode($code){
        $this->http_code = $code;
    }

    private  function getHttpCode(){
        return $this->http_code;
    }
    /**
     * 获取错误id
     * @return string
     */
    public function getErrorId()
    {
        return empty($this->error_id) ? 'ERROR' : $this->error_id;
    }

    /**
     * Report the exception.
     *
     * @param  \Illuminate\Http\Request
     * @return void
     */
    public function render($request)
    {
        return $this->result($request);

    }

    /**
     * 返回结果
     * @param $request
     * @return \Illuminate\Http\JsonResponse
     */
    private function result($request)
    {

        $http_code = $this->getCode();
        $data = self::formatApiData($this);
        return response()->json($data, $http_code);
    }

    public  function formatApiData(\Exception $e)
    {
        $error_code = $e->getErrorId();
        $error_msg = $e->getMessage();
        $http_code = $e->getCode();

        $data = [
            'code' => Handler::FAIL_CODE,
            'msg' => $error_msg,
            'data' => [],
            'http_code' => $this->getHttpCode(),
           // 'error_code' => $error_code,
        ];
        return $data;
    }
}
